package com.shenmazong.servermsgapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shenmazong.TbUserMessage;
import com.shenmazong.servermsgapi.mapper.TbUserMessageMapper;
import com.shenmazong.servermsgapi.service.MessageService;
import com.shenmazong.utils.ConstUtils;
import com.shenmazong.utils.ResponseResult;
import com.shenmazong.utils.SnowFlake;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    TbUserMessageMapper tbUserMessageMapper;

    /**
     * TODO sendMessage 发送普通消息
     * @param sendId
     * @param recvId
     * @param msgType
     * @param message
     * @return
     */
    @Override
    public ResponseResult sendMessage(Integer sendId, Integer recvId, Integer msgType, String message) {
        ResponseResult result = ResponseResult.SUCCESS();

        TbUserMessage msg = new TbUserMessage();
        msg.setSendid(sendId);
        msg.setRecvid(recvId);
        msg.setMsgtype(msgType);
        msg.setContent(message);

        SnowFlake snowFlake = new SnowFlake(2, 3);
        long id = snowFlake.nextId();
        msg.setId(id);

        rabbitTemplate.convertAndSend(ConstUtils.MQ_EXCHANGE_TOPIC_MSG_NAME, ConstUtils.MQ_QUEUE_TOPIC_MSG_NANE, msg);

        return result;
    }

    /**
     * TODO recvMessage 接收普通消息
     * @param userId
     * @param msgId
     * @return
     */
    @Override
    public ResponseResult recvMessage(Integer userId, Long msgId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> dataMap = new HashMap<>();

        //--1 检查用户是否合法

        //--2 获取消息
        List<TbUserMessage> messages = tbUserMessageMapper.selectList(new QueryWrapper<TbUserMessage>()
                .eq("recvid", userId)
                .gt("id", msgId)
                .orderByAsc("id"));
        if(messages == null || messages.size() == 0) {
            result.setCode(-1);
            result.setMessage("没有新消息");

            return result;
        }

        dataMap.put("messages", messages);

        //--3 设置发送标志
        UpdateWrapper<TbUserMessage> update = new UpdateWrapper<TbUserMessage>()
                .eq("recvid", userId)
                .gt("id", msgId)
                .set("status", 1);
        tbUserMessageMapper.update(null, update);

        result.setResult(dataMap);

        return result;
    }
}
